package hejie.admin.dao.impl;

import hejie.admin.dao.LoanTypeDao;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import publics.model.LoanType;


/**
 * @author  hejie
 * @version  1.0
 *  
 * 贷款种类增删查改Dao层接口实现
 */
//注入
@Component("loanTypeDao")
public class LoanTypeDaoImpl implements LoanTypeDao{

	HibernateTemplate hibernateTemplate;// 注入hibernate的spring代理模版

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	// 注入 hibernate模版
	@Resource(name = "hibernateTemplate")	
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
		System.out.println("hibernateTemplate injected in  LoanTypeDaoImpl.");
	}
	 

	public Integer save(LoanType ltype){
		return (Integer)this.getHibernateTemplate().save(ltype);
	}
	
	public boolean update(LoanType ltype){
		try{
			this.getHibernateTemplate().update(ltype);
		}catch (DataAccessException e) {
			System.out.println("执行到DaoIml的update异常.");
			return false;
		}
		return true;
	}
	
    public boolean deleteById(Integer id){
		System.out.println("LoanTypeDaoImpl里 id="+id);
    	try{
			this.hibernateTemplate.delete(this.getHibernateTemplate().get(LoanType.class, id));
    		
		}catch (DataAccessException e) {
			return false;
		}
		return true;
	}
    
	public boolean delete(LoanType ltype){
		try {
			 this.getHibernateTemplate().delete(ltype);
		} catch (DataAccessException e) {
			return false;
		}
	    return true;
	    	
	}
	
	public LoanType findById(Integer id){		
		return this.getHibernateTemplate().get(LoanType.class, id);
	}	
    
   @SuppressWarnings("unchecked")
   public List<LoanType> findByPage(final String hql, final int offset, final int pageSize) {
		List<LoanType> list = this.getHibernateTemplate().executeFind(
				new HibernateCallback() {
					public Object doInHibernate(Session session) throws HibernateException ,SQLException {
						List<LoanType> result = session.createQuery(hql)
							.setFirstResult(offset)
							.setMaxResults(pageSize)
							.list();
						return result;
					}
				}
				);
		
		return list;
	}
   
	public int findByCount(String sql) {	
		return this.getHibernateTemplate().find(sql).size();
	}

	@SuppressWarnings("unchecked")
	public List<LoanType> findByName(String name) {
		return this.getHibernateTemplate().find("from LoanType l where l.name = ? " , name);
	}

	@SuppressWarnings("unchecked")
	public List<LoanType> findByNum(Integer num) {
		return this.getHibernateTemplate().find("from LoanType l where l.num = ? " , num);
	}

}
